package com.jiayuge.server.config.security.component;

import com.jiayuge.server.pojo.Menu;
import com.jiayuge.server.pojo.Role;
import com.jiayuge.server.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 功能: 根据请求url分析请求所需的角色
 * 权限控制 获取能够访问url的角色
 *
 * @Program: yeb
 * @Date: 2021-11-18 18:25
 * @Author Jiayu.Yang
 */
@Component
public class CustomUrlRoleFilter implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private IMenuService menuService;

    AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 功能: 获取能够访问url的角色  |  访问url的权限  |  数据库: 增 | 删 | 改 | 查
     * * @param object
     * @return {@link Collection< ConfigAttribute>}
     * @Date 2021/11/18
     * @author jiayu.Yang
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //获取亲求url
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        //根据role查询菜单列表
        List<Menu> menus = menuService.getMenusWithRole();
        for (Menu menu : menus) {
            //将前端传入的url与每一个菜单的url进行匹配
            if (antPathMatcher.match(menu.getUrl(),requestUrl)){
//            if (antPathMatcher.match(requestUrl,menu.getUrl())){
                //stream过滤处理，只获取role字段的value 用String[] 接收
                String[] str = menu.getRoles().stream().map(Role::getName).toArray(String[]::new);
                //匹配通过的菜单，将能够访问的权限放入Security的全局配置中
                return SecurityConfig.createList(str);
            }
        }
        //没有匹配的url默认登录即可访问
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }


    @Override
    public boolean supports(Class<?> aClass) {
        return false;
    }
}
